//
//  NewTravelNoteViewController.m
//  TravelFollowYourHeart
//
//  Created by ENERGY on 2017/12/19.
//  Copyright © 2017年 Lwx. All rights reserved.
//

#import "NewTravelNoteViewController.h"
#import "IWTextView.h"
#import <CoreLocation/CoreLocation.h>
#import "ZYQAssetPickerController.h"
#import "SelectPicCollectionViewCell.h"
#import "AddressSelectedController.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "MyTravelViewController.h"


#import "ImmediateEvaluationViewController.h"
#import "ImmediateEvaluationTableViewCell.h"
#import "TZImagePickerController.h"
#import "UIPlaceHolderTextView.h"
#import "ImmediateEvaluationCollectionViewCell.h"
#import "MJPhotoBrowser.h"
#import "MJPhoto.h"
static NSString * const amapServiceKey = @"9fa9446d3fd67ff580e4694ed3e5aa6a";

#define TopViewH 50
#define Border 10
#define imageW (SCREEN_WIDTH - 5 * Border)/4
#define bottomBarH 50
@interface NewTravelNoteViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate, CLLocationManagerDelegate, UICollectionViewDelegate,UICollectionViewDataSource,ZYQAssetPickerControllerDelegate,UITableViewDelegate, UITableViewDataSource, TZImagePickerControllerDelegate, MJPhotoBrowserDelegate, ImmediateEvaluationTableViewCellDelegate>
@property (nonatomic, strong)UIView * topView;
@property (nonatomic, strong)UITextField * titleTextField;
@property (nonatomic, strong)UIView * middleView;
@property (nonatomic, strong)IWTextView * contentTextView;
@property (nonatomic, strong)UIButton * cameraBtn;
@property (nonatomic, strong)UIView * bottomView;
@property (nonatomic, strong)UIButton * locationBtn;
@property (nonatomic, strong)CLLocationManager * locationManager;
@property (nonatomic, strong)UIView * bottomBarView;
@property (nonatomic, strong)UICollectionView *collectionView;
@property (nonatomic, strong)UILabel * locationLab;

@property (nonatomic,strong) NSMutableArray *dataArray; //数据源
@property (nonatomic,strong) NSMutableArray *dataImageArray; // 存储选择的图片（二进制）
@property (nonatomic,strong) NSMutableArray *dataImageWithStrArray; // 上传图片返回的图片地址
@property (nonatomic,strong) NSData *imageWithData;

@property (nonatomic, strong)UIAlertController * alertController;
@property (nonatomic, strong)TZImagePickerController * imagePicker;
@property (nonatomic, strong)UIImagePickerController * imagePickerController;
@property (nonatomic,strong)NSMutableDictionary *objdic;

@property (nonatomic, strong)NSMutableArray * imageArray;
@property (nonatomic, assign)int state;
@end

@implementation NewTravelNoteViewController(Networking)
- (void)getDraftData{
    NSDictionary * dic = @{
                           @"mid":[UserModel intance].member_id,
                           @"token":[UserModel intance].token,
                           @"state":@(self.state),
                           @"title":self.titleTextField.text,
                           @"content":self.contentTextView.text,
                           @"location":self.locationLab.text,
                           @"lng":@([LocationTool shareIntance].longitude),
                           @"lat":@([LocationTool shareIntance].latitude)
                           };

    [[HttpRequest shardWebUtil]postNetworkRequestURLString:Url(@"/diary/writeDiary") andParas:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [self.imageArray removeObjectAtIndex:self.imageArray.count-1];
        for (UIImage *image in self.imageArray) {
            NSData *data = UIImageJPEGRepresentation(image, .1);
            NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
            [formData appendPartWithFileData:data name:@"pic[]" fileName:[NSString stringWithFormat:@"%ld.jpg",(NSUInteger)time] mimeType:@"image/jpeg"];
        }
    } andTransferGottenData:^(id obj, NSError *error) {
        if (error)
        {
            [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
        }
        else
        {
            if ([obj[@"code"] integerValue] == 100000) {
                
                [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
                [self.navigationController popViewControllerAnimated:YES];
                
            }else{
                [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
            }
        }
    }];
}

@end

@implementation NewTravelNoteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.view.backgroundColor = getColor(@"e5e5e5");
//    [self getDraftData];
    [self.view addSubview:self.topView];
    [self.topView addSubview:self.titleTextField];
    [self.view addSubview:self.middleView];
    [self.middleView addSubview:self.contentTextField];
    
    
    [self.middleView addSubview:self.collectionView];
    [self.middleView addSubview:self.cameraBtn];
    [self.view addSubview:self.bottomView];
    [self.bottomView addSubview:self.locationBtn];
    [self.bottomView addSubview:self.locationLab];
    [self.view addSubview:self.bottomBarView];
//    UIView * testView = [[UIView alloc] init];
//    [self.view addSubview:testView];
//    testView.backgroundColor = [UIColor redColor];
////    testView.frame = CGRectMake(0, self.bottomView.bottom + Border, SCREEN_WIDTH, 50);
//    [testView mas_makeConstraints:^(MASConstraintMaker *make) {
////        make.left.right.equalTo(self.bottomView);
////        make.left.equalTo(self.bottomView).offset(0);
////        make.right.equalTo(self.bottomView).offset(0);
//        make.left.mas_equalTo(self.bottomView.mas_left).offset(0);
//        make.right.mas_equalTo(self.bottomView.mas_right).offset(0);
//        make.top.mas_equalTo(self.bottomView.mas_bottom);
//        make.height.mas_equalTo(50/WIDTH_5S_SCALE);
//    }];
    
    //配置高德地图
    [AMapServices sharedServices].apiKey = amapServiceKey;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma init
- (UIView *)topView{
    if (!_topView) {
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, TopViewH)];
        _topView.layer.cornerRadius = 8;
        _topView.layer.masksToBounds = YES;
        _topView.backgroundColor = [UIColor whiteColor];
    }return _topView;
}

- (UITextField *)titleTextField{
    if (!_titleTextField) {
        _titleTextField = [[UITextField alloc] initWithFrame:CGRectMake(Border, 0, SCREEN_WIDTH - 2 * Border, 50)];
        _titleTextField.font = [UIFont systemFontOfSize:14.0];
        _titleTextField.placeholder = @"输入标题内容";
    }return _titleTextField;
}

- (UIView *)middleView{
    if (!_middleView) {
        _middleView = [[UIView alloc] init];
        _middleView.frame = CGRectMake(0, self.topView.bottom + Border, SCREEN_WIDTH, 200/HEIGHT_5S_SCALE);
        _middleView.backgroundColor = [UIColor whiteColor];
        _middleView.layer.cornerRadius = 8;
        _middleView.layer.masksToBounds = YES;
//        [_middleView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(self.topView).with.offset(Border);
//            make.left.mas_equalTo(0);
//            make.right.mas_equalTo(0);
//            make.height.mas_equalTo(50);
//        }];
    }return _middleView;
}

- (UITextView *)contentTextField{
    if (!_contentTextView) {
        _contentTextView = [[IWTextView alloc] init];
        _contentTextView.frame = CGRectMake(Border, Border, SCREEN_WIDTH - 2 * Border, self.middleView.height - 3 * Border - 130);
        _contentTextView.placeholder = @"请输入内容……";
        _contentTextView.font = [UIFont systemFontOfSize:14.0];
    }return _contentTextView;
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        int cellW = (SCREEN_WIDTH - 4 * Border)/3;
        UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 10;
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.itemSize = CGSizeMake(cellW, cellW);
//        layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
//        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(Border, self.contentTextView.bottom + Border, SCREEN_WIDTH - 2*Border, (SCREEN_HEIGHT - 5 * Border)/4/HEIGHT_5S_SCALE) collectionViewLayout:layout];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(Border, self.contentTextView.bottom + Border, SCREEN_WIDTH - 2*Border, (SCREEN_HEIGHT - 5 * Border)/4) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.bounces = NO;
        _collectionView.backgroundColor = [UIColor clearColor];
//        [_collectionView registerClass:[SelectPicCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([SelectPicCollectionViewCell class])];
        [_collectionView registerClass:[ImmediateEvaluationCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([ImmediateEvaluationCollectionViewCell class])];
//        layout.sectionInset = UIEdgeInsetsMake(0, 15, 0, 15);
        
//        _collectionView.backgroundColor = [UIColor redColor];
    }return _collectionView;
}

-(UIAlertController *)alertController
{
    if (!_alertController) {
        _alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从图库选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            _imagePicker = [[TZImagePickerController alloc]initWithMaxImagesCount:4 - self.imageArray.count delegate:self];
            _imagePicker.allowPickingVideo = NO;
            
            _imagePicker.allowTakePicture = NO;
            [self presentViewController:_imagePicker animated:YES completion:nil];
        }];
        UIAlertAction *addPhoneAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:self.imagePickerController animated:YES completion:nil];
            }
            else
            {
                //  [self showMessage:@"当前设备无摄像头，请从相册获取"];
            }
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [photoAction setValue:getColor(@"584f60@") forKey:@"_titleTextColor"];
        [addPhoneAction setValue:getColor(@"584f60@") forKey:@"_titleTextColor"];
        [cancelAction setValue:getColor(@"584f60@") forKey:@"_titleTextColor"];
        [_alertController addAction:photoAction];
        [_alertController addAction:addPhoneAction];
        [_alertController addAction:cancelAction];
    }
    return _alertController;
}

- (UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = [UIColor whiteColor];
        _bottomView.layer.cornerRadius = 8;
        _bottomView.layer.masksToBounds = YES;
        _bottomView.frame = CGRectMake(0, self.middleView.bottom + Border, SCREEN_WIDTH, self.topView.height);
    }return _bottomView;
}

- (UIView *)bottomBarView{
    if (!_bottomBarView) {
        _bottomBarView = [[UIView alloc] init];
        _bottomBarView.frame = CGRectMake(0, SCREEN_HEIGHT - 64 - 49, SCREEN_WIDTH, bottomBarH);
        UIButton * surePublishBtn = [[UIButton alloc] init];
        [surePublishBtn setTitle:@"确认发布" forState:UIControlStateNormal];
        surePublishBtn.titleLabel.font = DEF_FontSize_14;
        [surePublishBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [surePublishBtn setBackgroundColor:getColor(@"ffbb02")];
        surePublishBtn.frame = CGRectMake(0, 0, SCREEN_WIDTH / 2, bottomBarH);
        [surePublishBtn addTarget:self action:@selector(surePublishBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomBarView addSubview:surePublishBtn];
        
        UIButton * draftBtn = [[UIButton alloc] init];
        [draftBtn setTitle:@"存草稿箱" forState:UIControlStateNormal];
        draftBtn.titleLabel.font = DEF_FontSize_14;
        [draftBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [draftBtn setBackgroundColor:getColor(@"ffbb02")];
        draftBtn.frame = CGRectMake(SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2, bottomBarH);
        [draftBtn addTarget:self action:@selector(draftBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomBarView addSubview:draftBtn];
        
        UIView * lineView = [[UIView alloc] init];
        lineView.backgroundColor = [UIColor whiteColor];
        lineView.frame = CGRectMake(SCREEN_WIDTH / 2, 5, 1, bottomBarH - 5 * 2);
        [_bottomBarView addSubview:lineView];
    }return _bottomBarView;
}

- (UIButton *)locationBtn{
    if (!_locationBtn) {
        _locationBtn = [[UIButton alloc] init];
        _locationBtn.frame = CGRectMake(Border, Border, 85, self.bottomView.height - 2 * Border);
        [_locationBtn setImage:[UIImage imageNamed:@"yj_location"] forState:UIControlStateNormal];
        [_locationBtn setTitle:@"所在位置" forState:UIControlStateNormal];
        [_locationBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _locationBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
        [_locationBtn addTarget:self action:@selector(locationBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
    }return _locationBtn;
}

- (UILabel *)locationLab{
    if (!_locationLab) {
        _locationLab = [[UILabel alloc] init];
        _locationLab.font = DEF_FontSize_14;
        _locationLab.textColor = [UIColor blackColor];
        _locationLab.textAlignment = NSTextAlignmentLeft;
        _locationLab.frame = CGRectMake(self.locationBtn.right, Border, SCREEN_WIDTH - Border - self.locationBtn.right, self.bottomView.height - 2 * Border);
    }return _locationLab;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}

- (NSMutableArray *)dataImageArray
{
    if (!_dataImageArray) {
        _dataImageArray = [NSMutableArray array];
    }
    return _dataImageArray;
}

-(NSMutableArray *)imageArray
{
    if (!_imageArray) {
        _imageArray = [NSMutableArray arrayWithArray:@[[UIImage imageNamed:@"fankui"]]];
    }
    return _imageArray;
}

-(UIImagePickerController *)imagePickerController
{
    if (!_imagePickerController) {
        _imagePickerController = [[UIImagePickerController alloc]init];
        _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = YES;
    }
    return _imagePickerController;
}

- (NSMutableArray *)dataImageWithStrArray
{
    if (!_dataImageWithStrArray) {
        _dataImageWithStrArray = [NSMutableArray array];
    }
    return _dataImageWithStrArray;
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.imageArray.count < 4) {
        return self.imageArray.count;
    }
    return self.imageArray.count - 1;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ImmediateEvaluationCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([ImmediateEvaluationCollectionViewCell class]) forIndexPath:indexPath];
    cell.imageView.image = self.imageArray[indexPath.row];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.imageArray.count < 4) {
        if (indexPath.row == self.imageArray.count - 1) {
            [self presentViewController:self.alertController animated:YES completion:nil];
            return;
        }
    }
    //1.创建图片浏览器
    MJPhotoBrowser *brower = [[MJPhotoBrowser alloc] init];
    //2.告诉图片浏览器显示所有的图片
    NSMutableArray *photos = [NSMutableArray array];
    for (int i = 0 ; i < self.imageArray.count - 1; i++) {
        //传递数据给浏览器
        MJPhoto *mjPhoto = [[MJPhoto alloc] init];
        mjPhoto.image = self.imageArray[i];
        ImmediateEvaluationCollectionViewCell *cell = (ImmediateEvaluationCollectionViewCell*)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        mjPhoto.srcImageView = cell.imageView; //设置来源哪一个UIImageView
        [photos addObject:mjPhoto];
    }
    brower.photos = photos;
    brower.isShowDeleteButton = YES;
    brower.delegate = self;
    //3.设置默认显示的图片索引
    brower.currentPhotoIndex = indexPath.row;
    //4.显示浏览器
    [brower show];
}

#pragma mark - MJPhotoBrowserDelegate

-(void)photoBrowser:(MJPhotoBrowser *)photoBrowser didDeletePhotoAtIndex:(NSInteger)index
{
    if (index < self.imageArray.count) {
        UIImage *image = self.imageArray[index];
        [self.imageArray removeObject:image];
        [self.collectionView reloadData];
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (self.imageArray.count >=4) {
        [[HUDHelper sharedInstance] tipMessage:@"您最多选择3张照片"];
        return;
    }
    [self.imageArray insertObject:image atIndex:self.imageArray.count - 1];
    [_collectionView reloadData];
}

-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        ALAssetsLibrary *library  = [[ALAssetsLibrary alloc] init];
        [library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
            if (error) {
                // TODO: error handling
            } else {
                [library  assetForURL:assetURL resultBlock:^(ALAsset *asset) {
//                    [self.selectPhotos addObject:asset];
//                    [_imageCollection reloadData];
                    [self.imageArray insertObject:image atIndex:self.imageArray.count - 1];
                    [_collectionView reloadData];
                } failureBlock:^(NSError *error) {
                    
                }];
            }
        }];
    }
}


- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos
{
    if (self.imageArray.count + photos.count > 4) {
        [[HUDHelper sharedInstance] tipMessage:@"您最多选择3张照片"];
        return;
    }
    [self.imageArray removeObjectAtIndex:self.imageArray.count - 1];
    [self.imageArray addObjectsFromArray:photos];
    [self.imageArray addObject:[UIImage imageNamed:@"fankui"]];
    
    [_collectionView reloadData];
}


#pragma action
- (void)transformPicture{
    NSLog(@"传照片");
}

- (void)surePublishBtnClick{
    NSLog(@"确认发布");
    self.state = 1;
    if (self.imageArray.count == 1) {
        [[HUDHelper sharedInstance]tipMessage:@"请选取游记图片"];
    }else if (self.locationLab.text == nil){
        [[HUDHelper sharedInstance]tipMessage:@"请选取位置"];
    }else{
        [self getDraftData];
        for (UIViewController *controller in self.navigationController.viewControllers) {
            if ([controller isKindOfClass:[MyTravelViewController class]]) {
                MyTravelViewController *vc = (MyTravelViewController *)controller;
                vc.isPublish = YES;
                [self.navigationController popToViewController:vc animated:YES];
            }
        }
    }
}

- (void)draftBtnClick{
    NSLog(@"存草稿箱");
    self.state = 2;
    if (self.imageArray.count == 1) {
        [[HUDHelper sharedInstance]tipMessage:@"请选取游记图片"];
    }else if (self.locationLab.text == nil){
        [[HUDHelper sharedInstance]tipMessage:@"请选取位置"];
    }else{
        {
            [self getDraftData];
            for (UIViewController *controller in self.navigationController.viewControllers) {
                if ([controller isKindOfClass:[MyTravelViewController class]]) {
                    MyTravelViewController *vc = (MyTravelViewController *)controller;
                    vc.isPublish = NO;
                    [self.navigationController popToViewController:vc animated:YES];
                }
            }
        }
    }
}

- (void)locationBtnClick{
    AddressSelectedController * addressSelectedVC = [[AddressSelectedController alloc] init];
    addressSelectedVC.completeBlock = ^(DDLocationReGeocode *reGeocode, NSError *error) {
        
        NSLog(@"%@,%@,%f,%f",reGeocode.name,reGeocode.address,reGeocode.coordinate.latitude,reGeocode.coordinate.longitude);
        self.locationLab.text = reGeocode.name;
        
    };
    addressSelectedVC.currentCoordinate = CLLocationCoordinate2DMake([LocationTool shareIntance].latitude,[LocationTool shareIntance].longitude);
    [self.navigationController pushViewController:addressSelectedVC animated:YES];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.titleTextField resignFirstResponder];
    [self.contentTextView resignFirstResponder];
}

@end
